package com.hzya.frame.web.tag;

import com.hzya.frame.system.module.dao.IModuleDao;
import com.hzya.frame.system.module.entity.ModuleEntity;
import com.hzya.frame.system.user.entity.UserEntity;
import com.hzya.frame.utils.help.FreemarkerHelper;
import com.hzya.frame.utils.help.RegexpHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.util.*;

public class ButtonTag extends TagSupport {

	@Autowired
	private IModuleDao systemModuleDao;

	private HttpServletRequest httpServletRequest;

	private HttpServletResponse httpServletRespons;

	private UserEntity getCurrentUser() {
		HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
		return (UserEntity) request.getSession().getAttribute("_CURRENT_USER");
	}

	public void init() {
		httpServletRespons = (HttpServletResponse) this.pageContext.getResponse();
		httpServletRequest = (HttpServletRequest) this.pageContext.getRequest();
		ServletContext servletContext = this.pageContext.getServletContext();
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
		systemModuleDao = (IModuleDao) wac.getBean("system_moduledao");

	}
	@Override
	public int doEndTag() throws JspException {
		init();
		UserEntity userEntity = getCurrentUser();
		List<ModuleEntity> tempList = userEntity.getModulesList();
		ModuleEntity systemModuleDomain = getMathModuleDomain();
		if (null != systemModuleDomain) {
			try {
			List<ModuleEntity> resultList = getMatchModules(systemModuleDomain, tempList);
			StringBuilder tag = new StringBuilder("<!--=================权限按钮组 start==================-->\n");

			for (ModuleEntity tempDomain : resultList) {
				tag.append(tempDomain.getHtm_content() + "\n");
			}
			tag.append("<!--=================权限按钮组 end==================-->\n");
			Map root = new HashMap();
			root.put("base", httpServletRequest.getContextPath());
			JspWriter out = this.pageContext.getOut();
			String result = FreemarkerHelper.process(null, tag.toString(), root);
				out.print(result);
				out.flush();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			}
		}

		return super.doEndTag();
	}

	@Override
	public int doAfterBody() throws JspException {
		return super.doAfterBody();
	}

	@Override
	public int doStartTag() throws JspException {
		return EVAL_PAGE;
	}

	/**
	 * 获得最匹配模块
	 * 
	 * @return
	 */
	private ModuleEntity getMathModuleDomain() {
		HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
		String requestUrl = String.valueOf(request.getRequestURL());
		ModuleEntity matchesDomain = null;
		List<ModuleEntity> allModuleList = systemModuleDao.getAllExp();
		for (ModuleEntity tempDomain : allModuleList) {
			if (tempDomain.getUrl_pattern() != null && !"".equals(tempDomain.getUrl_pattern()) &&  RegexpHelper.isGlobmatches(requestUrl.toLowerCase(), tempDomain.getUrl_pattern().toLowerCase())) {
				if (matchesDomain == null) {
					matchesDomain = tempDomain;
				} else {
					if (matchesDomain.getLvl() != null && tempDomain.getLvl() != null && tempDomain.getLvl().compareTo(matchesDomain.getLvl()) > 0) {
						matchesDomain = tempDomain;
					}
				}
			}
		}
		return matchesDomain;
	}

	/**
	 * 获得有权限的按钮列表
	 * 
	 * @param moduleEntity
	 * @return
	 */
	public List<ModuleEntity> getMatchModules(ModuleEntity moduleEntity, List<ModuleEntity> userModuleList) {
		moduleEntity.setType("button");
		moduleEntity.setSort("order_num");
		moduleEntity.setOrder("ASC");
		List<ModuleEntity> childList = systemModuleDao.getChildList(moduleEntity);
		List<ModuleEntity> resultList =   new ArrayList<ModuleEntity>(childList);
		resultList.retainAll(userModuleList);

		Collections.sort(childList);

		return resultList;

	}

}
